﻿using HsServerHa.Common;
using HsServerHa.Common.Auth;
using HsServerHa.Core.Http;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.SQLite;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HsServerHa.UserControls
{
    /// <summary>
    /// SystemSettingManage.xaml 的交互逻辑
    /// </summary>
    public partial class SystemSettingManage : UserControl
    {
        public SystemSettingManage()
        {
            InitializeComponent();
            InitData();
        }
        public void InitData() {
            this.currentPage.Content = new PassworkEdit();
            this.currentPage1.Content = new AlarmPushManage();
            this.currentPage2.Content = new InitSysSetting();
            var isAutoSwitch = (IniFileConfig.Current.GetStringValue("UserConfig", "IsAutoSwitch") ?? "true").ToBool();
            this.IsAutoSwitch.IsChecked = isAutoSwitch;

            this.IsStartAutoSwitch.IsChecked = InitSysSettingHelper.GetAutoStart();

            var isStartDaemon = (IniFileConfig.Current.GetStringValue("UserConfig", "isStartDaemon") ?? "true").ToBool();
            this.IsStartDaemon.IsChecked = isStartDaemon;

            var IsStartSyncFile = (IniFileConfig.Current.GetStringValue("UserConfig", "IsStartSyncFile") ?? "true").ToBool();
            this.IsStartSyncFile.IsChecked = IsStartSyncFile;
        }

        private void navigationPanel_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            e.Handled = true;
        }

        private void IsAutoSwitch_Checked(object sender, RoutedEventArgs e)
        {
            SwitchFun(true);
        }

        private void IsAutoSwitch_Unchecked(object sender, RoutedEventArgs e)
        {
            SwitchFun(false);
        }

        private void SwitchFun(bool checkVal)
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }
            #endregion

            try
            {
                if (App.isMaster == null)
                {
                    AduMessageBoxs.Show("系统配置错误！");
                    return;
                }
                if (checkVal != (IniFileConfig.Current.GetStringValue("UserConfig", "IsAutoSwitch") ?? "true").ToBool())
                {
                    var paramsStr = new AutoSwitchEntity
                    {
                        IsAutoSwitch = checkVal + ""
                    };
                    List<MasterSlaveBindEntity> listBind = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
                    var bindFirst = listBind.FirstOrDefault();
                    if (bindFirst != null)
                    {
                        var path = "";
                        if (App.isMaster.Value)
                        {
                            path = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                        }
                        else
                        {
                            path = $"http://{bindFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                        }
                        var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(path + ConfigurationManager.AppSettings["postAutoUpdateSwatch"]?.ToString() ?? "postAutoUpdateSwatch", JsonConvert.SerializeObject(paramsStr)).Result;
                        if (result == null)
                        {

                            AduMessageBoxs.Show($"切换失败,请检查主从是否联机状态！");
                            return;
                        }
                        if (result.IsSuccess)
                        {
                            IniFileConfig.Current.SetStringValue("UserConfig", "IsAutoSwitch", checkVal + "");
                            AduMessageBoxs.Show("切换成功！");
                            return;
                        }
                        else
                        {
                            AduMessageBoxs.Show("切换失败！");
                            LoggerHelper.Error(result.ErrorMessage, "Switch");
                            return;

                        }
                    }

                }
            }
            catch (Exception ex)
            {
                AduMessageBoxs.Show(ex.Message);
                LoggerHelper.Error(ex.Message, "自动切换主从");
                return;
            }

        }

        private void IsStartAutoSwitch_Unchecked(object sender, RoutedEventArgs e)
        {
            SwitchStartAutoFun(false);
        }

        private void IsStartAutoSwitch_Checked(object sender, RoutedEventArgs e)
        {
            SwitchStartAutoFun(true);
        }
        private void SwitchStartAutoFun(bool checkVal) {

            var val = false;
            val = InitSysSettingHelper.GetAutoStart();

            if (val!=checkVal)
            {
                var paramsStr = new AutoSwitchEntity
                {
                    IsAutoSwitch = checkVal + ""
                };
                List<MasterSlaveBindEntity> listBind = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
                var bindFirst = listBind.FirstOrDefault();
                if (bindFirst != null)
                {
                    var path = "";
                    if (App.isMaster.Value)
                    {
                        path = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    }
                    else
                    {
                        path = $"http://{bindFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    }
                    var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(path + ConfigurationManager.AppSettings["postAutoStartUpdateSwatch"]?.ToString() ?? "postAutoStartUpdateSwatch", JsonConvert.SerializeObject(paramsStr)).Result;
                    if (result == null)
                    {

                        AduMessageBoxs.Show($"切换失败,请检查主从是否联机状态！");
                        return;
                    }
                    if (result.IsSuccess)
                    {
                        InitSysSettingHelper.SetAutoStart(checkVal);
                        AduMessageBoxs.Show("切换成功！");
                        return;
                    }
                    else
                    {
                        AduMessageBoxs.Show("切换失败！");
                        LoggerHelper.Error(result.ErrorMessage, "StartAutoSwitch");
                        return;

                    }
                }
            }
        }

        private void IsStartDaemon_Checked(object sender, RoutedEventArgs e)
        {
            SwitchStartDaemonFun(true);
        }

        private void IsStartDaemon_Unchecked(object sender, RoutedEventArgs e)
        {
            SwitchStartDaemonFun(false);
        }

        /// <summary>
        /// 开启进程守护
        /// </summary>
        /// <param name="checkVal"></param>
        private void SwitchStartDaemonFun(bool checkVal)
        {
            var isStartDaemon = (IniFileConfig.Current.GetStringValue("UserConfig", "isStartDaemon") ?? "true").ToBool();

            if (isStartDaemon != checkVal)
            {
                var paramsStr = new AutoSwitchEntity
                {
                    IsAutoSwitch = checkVal + ""
                };
                List<MasterSlaveBindEntity> listBind = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
                var bindFirst = listBind.FirstOrDefault();
                if (bindFirst != null)
                {
                    var path = "";
                    if (App.isMaster.Value)
                    {
                        path = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    }
                    else
                    {
                        path = $"http://{bindFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    }
                    var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(path + ConfigurationManager.AppSettings["postStartDaemonUpdateSwatch"]?.ToString() ?? "postStartDaemonUpdateSwatch", JsonConvert.SerializeObject(paramsStr)).Result;
                    if (result == null)
                    {

                        AduMessageBoxs.Show($"切换失败,请检查主从是否联机状态！");
                        return;
                    }
                    if (result.IsSuccess)
                    {
                        IniFileConfig.Current.SetStringValue("UserConfig", "IsStartDaemon", checkVal + "");
                        AduMessageBoxs.Show("切换成功！");
                        return;
                    }
                    else
                    {
                        AduMessageBoxs.Show("切换失败！");
                        LoggerHelper.Error(result.ErrorMessage, "StartDaemonSwitch");
                        return;

                    }
                }
            }
        }

        private void IsStartSyncFile_Checked(object sender, RoutedEventArgs e)
        {
            SwitchStartSyncFileFun(true);
        }

        private void IsStartSyncFile_Unchecked(object sender, RoutedEventArgs e)
        {
            SwitchStartSyncFileFun(false);
        }

        private void SwitchStartSyncFileFun(bool checkVal)
        {
            var isStartDaemon = (IniFileConfig.Current.GetStringValue("UserConfig", "IsStartSyncFile") ?? "true").ToBool();

            if (isStartDaemon != checkVal)
            {
                var paramsStr = new AutoSwitchEntity
                {
                    IsAutoSwitch = checkVal + ""
                };
                List<MasterSlaveBindEntity> listBind = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();
                var bindFirst = listBind.FirstOrDefault();
                if (bindFirst != null)
                {
                    var path = "";
                    if (App.isMaster.Value)
                    {
                        path = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    }
                    else
                    {
                        path = $"http://{bindFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    }
                    var result = HttpHelpers.PostToJson<HttpResponseResultModel<object>>(path + ConfigurationManager.AppSettings["postStartSyncFileUpdateSwatch"]?.ToString() ?? "postStartSyncFileUpdateSwatch", JsonConvert.SerializeObject(paramsStr)).Result;
                    if (result == null)
                    {

                        AduMessageBoxs.Show($"切换失败,请检查主从是否联机状态！");
                        return;
                    }
                    if (result.IsSuccess)
                    {
                        IniFileConfig.Current.SetStringValue("UserConfig", "IsStartSyncFile", checkVal + "");
                        AduMessageBoxs.Show("切换成功！");
                        return;
                    }
                    else
                    {
                        AduMessageBoxs.Show("切换失败！");
                        LoggerHelper.Error(result.ErrorMessage, "IsStartSyncFile");
                        return;

                    }
                }
            }
        }
    }
}
